package com.szmg.wishwalls.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.szmg.wishwalls.dao.ProductionDao;
import com.szmg.wishwalls.dao.WishOrderDao;
import com.szmg.wishwalls.dto.DiscussDto;
import com.szmg.wishwalls.dto.ProductionDto;
import com.szmg.wishwalls.dto.VoteDetailDto;
import com.szmg.wishwalls.dto.VoteSortDto;
import com.szmg.wishwalls.dto.WishOrderDetailDto;
import com.szmg.wishwalls.model.Discuss;
import com.szmg.wishwalls.model.OrderProductionRelation;
import com.szmg.wishwalls.model.Production;
import com.szmg.wishwalls.model.Program;
import com.szmg.wishwalls.model.VoteDetail;
import com.szmg.wishwalls.model.WishOrder;
import com.szmg.wishwalls.service.WishOrderService;
import com.szmg.wishwalls.util.WishWalleException;

@Service("wishOrderService")
public class WishOrderServiceImpl implements WishOrderService{
	@Resource(name="wishOrderDao")
	private WishOrderDao wishOrderDao;
	
	@Resource(name="productionDao")
	private ProductionDao productionDao;
	
	@Transactional(propagation = Propagation.REQUIRED)
	public void saveWishOrder(WishOrder wishOrder,String programCode,String[] productionIds){
		try{
			if(null == wishOrder || StringUtils.isEmpty(wishOrder.getWechatId()) || StringUtils.isEmpty(programCode)) return;
			Program program = wishOrderDao.queryProgramByCode(programCode);
			if(null == program) return;
			wishOrder.setProgramId(program.getId());
			wishOrderDao.saveWishOrder(wishOrder);
			if(null != productionIds && productionIds.length > 0){//保存关联心愿单玉产品的关联关系
				for(String productionId : productionIds){
					OrderProductionRelation relation = new OrderProductionRelation(wishOrder.getId(),productionId);
					wishOrderDao.saveOrderProductionRelation(relation);
				}
			}
		}catch(Exception e){
			throw new WishWalleException("WishOrderServiceImpl saveWishOrder error:",e);
		}
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	public void saveVoteDetail(VoteDetailDto voteDetailDto){
		try{
			if(null == voteDetailDto) return;
			//获取心愿单和产品的关联记录
			OrderProductionRelation relation = wishOrderDao.queryOrderProductionRelation(voteDetailDto.getWishOrderId(),voteDetailDto.getProductionId());
			if(null == relation) return;
			VoteDetail voteDetail = new VoteDetail();
			voteDetail.setOrderProductionRelationId(relation.getId());
			voteDetail.setWechatId(voteDetailDto.getWechatId());
			wishOrderDao.saveVoteDetail(voteDetail);
			wishOrderDao.updateVoteCountById(relation.getId());
		}catch(Exception e){
			throw new WishWalleException("WishOrderServiceImpl saveVoteDetail error:",e);
		}
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	public void saveDiscuss(Discuss discuss,String discussParentId){
		try{
			if(null == discuss) return;
			//默认设置为第一个评论，没有回复信息
			discuss.setParentId("0");
			wishOrderDao.saveDiscuss(discuss);
		}catch(Exception e){
			throw new WishWalleException("WishOrderServiceImpl saveDiscuss error:",e);
		}
	}
	
	@Transactional(propagation = Propagation.SUPPORTS)
	public WishOrder queryWishOrderByWechatId(String wechatId,String programCode){
		try{
			return wishOrderDao.queryWishOrderByWechat(wechatId,programCode);
		}catch(Exception e){
			throw new WishWalleException("WishOrderServiceImpl queryWishOrderByWechatId error:",e);
		}
	}
	
	@Transactional(propagation = Propagation.SUPPORTS)
	public List<DiscussDto> queryDiscussByWishOrderId(String wishOrderId){
		try{
			List<Discuss> dicussList = wishOrderDao.queryDiscussByWishOrderId(wishOrderId);
			if(CollectionUtils.isEmpty(dicussList)) return Collections.emptyList();
			List<Discuss> rootDicuss = new ArrayList<Discuss>(dicussList.size());
			//key为第一次评论的id
			Map<String,List<Discuss>> map = new HashMap<String,List<Discuss>>();
			for(Discuss discuss : dicussList){
				if("0".equals(discuss.getParentId())){//根评论
					rootDicuss.add(discuss);
				}else{//对所有第一个评论进行的回复进行划分
					List<Discuss> list = map.get(null != discuss.getParentId()?discuss.getParentId():"");
					if(CollectionUtils.isEmpty(list)){
						list = new ArrayList<Discuss>();
					}
					list.add(discuss);
					map.put(discuss.getParentId(), list);
				}
			}
			
			List<DiscussDto> discussDtoList = new ArrayList<DiscussDto>(rootDicuss.size());
			DiscussDto dto = null;
			for(Discuss discuss : rootDicuss){//对第一个评论的回复进行赋值
				dto = new DiscussDto();
				dto.setDiscuss(discuss);
				if(null == map.get(discuss.getId())){
					dto.setDiscussList(Collections.EMPTY_LIST);
				}else{
					dto.setDiscussList(map.get(discuss.getId()));
				}
				discussDtoList.add(dto);
			}
			return discussDtoList;
		}catch(Exception e){
			throw new WishWalleException("WishOrderServiceImpl queryDiscussByWishOrderId error:",e);
		}
	}
	
	@Transactional(propagation = Propagation.SUPPORTS)
	public List<VoteDetail> queryVoteDetailsByRelationId(String wishOrderId,String productionId){
		try{
			return wishOrderDao.queryVoteDetailsByRelationId(wishOrderId,productionId);
		}catch(Exception e){
			throw new WishWalleException("WishOrderServiceImpl queryVoteDetailsByRelationId error:",e);
		}
	}
	
	@Transactional(propagation = Propagation.SUPPORTS)
	public WishOrderDetailDto queryWishOrderDtoById(String wishOrderId){
		WishOrder order = wishOrderDao.queryWishOrderById(wishOrderId);
		if(null == order) return null;
		WishOrderDetailDto orderDto = new WishOrderDetailDto();
		orderDto.setWishOrder(order);
		orderDto.setDiscussList(wishOrderDao.queryDiscussByWishOrderId(wishOrderId));
		
		List<Production> productionList = productionDao.queryProductionByWishOrderId(wishOrderId);
		if(CollectionUtils.isEmpty(productionList)) return orderDto;
		
		 List<ProductionDto> productionDtos = new ArrayList<ProductionDto>(productionList.size());
		for(Production production : productionList){
			ProductionDto dto = new ProductionDto();
			dto.setProduction(production);
			dto.setVoteSortDtoList(wishOrderDao.queryWishOrderDto(order.getProgramId(), production.getId()));
			productionDtos.add(dto);
		}
		orderDto.setProductionDtoList(productionDtos);
		return orderDto;
	}
	
	@Transactional(propagation = Propagation.SUPPORTS)
	public boolean checkIsHadWishOrder(String wechatId,String programCode){
		if(StringUtils.isEmpty(wechatId) || StringUtils.isEmpty(programCode)) return false;
		WishOrder order = wishOrderDao.queryWishOrderByWechat(wechatId, programCode);
		if(null == order) return false;
		return true;
	}
	
	@Transactional(propagation = Propagation.SUPPORTS)
	public void updateWishOrder(String wishOrderId,String wishDeclaration){
		if(StringUtils.isEmpty(wishOrderId) || StringUtils.isEmpty(wishDeclaration)) return;
		wishOrderDao.updateWishOrder(wishOrderId, wishDeclaration);
	}


	public WishOrder queryWishOrderById(String wishOrderId){
		return wishOrderDao.queryWishOrderById(wishOrderId);
	}
	
	public List<VoteSortDto> queryWishOrderDto(String programId, String productionId,String wechatId){
		List<VoteSortDto> list = wishOrderDao.queryWishOrderDto(programId, productionId);
		if(CollectionUtils.isEmpty(list)) return Collections.emptyList();
		
		List<VoteSortDto> resultList = new ArrayList<VoteSortDto>(list.size());
		VoteSortDto dto;
		VoteSortDto selfDto = new VoteSortDto();
		for(int i=0;i<list.size();i++){
			dto = list.get(i);
			dto.setSort(i+1);
			if(null != wechatId && wechatId.equals(dto.getWechat())){
				selfDto = dto;
			}else{
				resultList.add(dto);
			}
		}
		List<VoteSortDto> returnList = new ArrayList<VoteSortDto>(list.size());
		returnList.add(selfDto);
		returnList.addAll(resultList);
		return returnList;
	}
	
	public boolean checkHadVoted(VoteDetailDto voteDetailDto){
		VoteDetail voteDetail = wishOrderDao.queryVoteDetailsByWechatId(voteDetailDto);
		if(null == voteDetail) return false;
		return true;
	}
	
	public void superAllProduction(String wishOrderId,String openId){
		List<OrderProductionRelation> relationList = wishOrderDao.queryOrderProductionRelationList(wishOrderId);
		if(CollectionUtils.isEmpty(relationList)) return;
		//记录满足投票条件的id
		List<String> relationIds = new ArrayList<String>(10);
		List<VoteDetail> voteList = null;
		VoteDetail voteDetail = null;
		for(OrderProductionRelation relation : relationList){
			voteList = wishOrderDao.queryVoteDetailsByRelationAndOpenId(relation.getId(),openId);
			if(CollectionUtils.isEmpty(voteList)){//没有投票记录
				relationIds.add(relation.getId());
				voteDetail = new VoteDetail();
				voteDetail.setOrderProductionRelationId(relation.getId());
				voteDetail.setWechatId(openId);
				wishOrderDao.saveVoteDetail(voteDetail);
			}
		}
		if(CollectionUtils.isEmpty(relationIds)) return;
		//存在没有投票的记录，进行投票
		wishOrderDao.superAllProduction(relationIds);
	}

	
}
